import importlib
import os

import pytest


def _has_psycopg() -> bool:
    try:
        import psycopg  # noqa: F401
        return True
    except Exception:
        return False


def test_cluster_mode_falls_back_to_sqlite(monkeypatch):
    # Request cluster without DSN; expect get_store_mode to report sqlite fallback
    from tldw_Server_API.app.core.config import clear_config_cache

    monkeypatch.setenv("SANDBOX_STORE_BACKEND", "cluster")
    monkeypatch.delenv("SANDBOX_STORE_PG_DSN", raising=False)
    monkeypatch.delenv("DATABASE_URL", raising=False)
    clear_config_cache()

    from tldw_Server_API.app.core.Sandbox import store as sbx_store
    importlib.reload(sbx_store)

    mode = sbx_store.get_store_mode()
    assert mode == "sqlite"


@pytest.mark.integration
def test_cluster_mode_smoke_with_postgres(monkeypatch):
    # Requires SANDBOX_TEST_PG_DSN and psycopg installed
    dsn = os.getenv("SANDBOX_TEST_PG_DSN")
    if not dsn or not _has_psycopg():
        pytest.skip("Postgres DSN not provided or psycopg not installed")

    from tldw_Server_API.app.core.config import clear_config_cache

    monkeypatch.setenv("SANDBOX_STORE_BACKEND", "cluster")
    monkeypatch.setenv("SANDBOX_STORE_PG_DSN", dsn)
    clear_config_cache()

    from tldw_Server_API.app.core.Sandbox import store as sbx_store
    importlib.reload(sbx_store)

    assert sbx_store.get_store_mode() == "cluster"

    # Basic connectivity check: construct store and call a simple method
    st = sbx_store.get_store()
    assert hasattr(st, "count_runs")
    # Should not raise
    _ = int(st.count_runs())
